import vtkFullScreenRenderWindow from '@kitware/vtk.js/Rendering/Misc/FullScreenRenderWindow'
import vtkXMLImageDataReader from "@kitware/vtk.js/IO/XML/XMLImageDataReader";
import vtkVolumeMapper from "@kitware/vtk.js/Rendering/Core/VolumeMapper";
import vtkVolume from "@kitware/vtk.js/Rendering/Core/Volume";
import vtkColorTransferFunction from "@kitware/vtk.js/Rendering/Core/ColorTransferFunction";
import vtkPiecewiseFunction from "@kitware/vtk.js/Common/DataModel/PiecewiseFunction";

function test(){
    console.log("测试")
}

// rootContainer：页面容器元素、fileContents：图像文件、options：容器配置
function createViewer(rootContainer, fileContents, options){
    const background = options.background
    ? options.background.split(',').map((s) => Number(s)): [0,0,0]; // 创建背景色为黑色

    const containerStyle = options.containerStyle;

    // 创建新的FullScreenRenderWindow实例
    const fullScreenRenderer = vtkFullScreenRenderWindow.newInstance( {
        background,
        rootContainer,
        containerStyle
    })

    const renderer = fullScreenRenderer.getRenderer(); // 获取渲染器对象
    const renderWindow = fullScreenRenderer.getRenderWindow(); // 获取渲染窗口对象
    renderWindow.getInteractor().setDesiredUpdateRate(30); // 设置交互器的期望更新速率，设置为30帧

    // 初始化ImageDataReader对象，用于解析VTK XML对象的输入
    const vitReader = vtkXMLImageDataReader.newInstance();
    vitReader.parseAsArrayBuffer(fileContents); // 从XML格式的文件中读取图像数据，解析到ArrayBuffer中
    const source = vitReader.getOutputData(0); // 获取图像数据

    // 创建mapper 和 actor
    const mapper = vtkVolumeMapper.newInstance();
    const actor = vtkVolume.newInstance();

    // 检索数据对象关联的标量数据，以便使用它创建数据的可视化效果，标量数据通常用于确定可视化中像素或体素的颜色和不透明度
    const dataArray = source.getPointData().getScalars() || source.getPointData().getArrays()[0];
    const dataRange = dataArray.getRange(); // 检索数据数组中的值，对获得的点数进行归一化处理

    // 实例化ColorTransferFunction和PiecewiseFunction
    // ColorTransferFunction用于对RGB或HSV空间中的颜色映射
    // PiecewiseFunction是定义分段函数映射，允许添加控制点，并允许用户控制控制点之间的距离
    const lookupTable = vtkColorTransferFunction.newInstance();
    const piecewiseFunction = vtkPiecewiseFunction.newInstance();

    // 填充管道(给actor添加mapper，给mapper设置输入数据，给renderer添加actor)
    actor.setMapper(mapper);
    mapper.setInputData(source);
    renderer.addActor(actor);

    // 配置
    const sampleDistance =
        0.7 *
        Math.sqrt(
            source
                .getSpacing()
                .map((v) => v*v)
                .reduce((a,b) => a+b, 0)
        );
    mapper.setSampleDistance(sampleDistance);

}

export {
    test
}